const towxml = require('../../towxml/index')
const { request } = require('../../services/request')
const baseUrl = 'ws://chunfengai.top:28081'
const app = getApp()
const systemInfo = wx.getSystemInfoSync()
const log = require('../../utils/log')
    // const baseUrl = 'ws://127.0.0.1:8080'
    /**
     * 进入逻辑
     * 首页进入->欢迎语->咨询人（获得userId\awnsuserid）->创建新对话->推荐问题->对话
     * 历史记录进入->上个页面带进userId\awnsuserid\id->显示历史记录
     */
const registerEvent = () => {
    wx.onKeyboardHeightChange((res) => {
        console.log('res :>> ', res);
    })
}
Page({
    /**
     * 页面的初始数据
     */
    data: {
        dataInfo: {
            good: true,
        },
        questionList: ['推荐问题1', '推荐问题1', '推荐问题1'],
        socketOpen: false,
        msg: '',
        dialogues: [],
        userId: '',
        answeUserInfo: { answeUserName: 'name', sex: 0, age: 19 },
        answeUserId: '',
        appMenuId: '',
        dialogueId: '',
        channelData: {}, // 首次创建对话的 频道数据 描述 问题列表 点赞
        loading: false,
        inputHeight: 0,
        title: '',
        menuId: '',
        typing: false,
        wsStack: [],
        paddingBottom: 10 + app.globalData.footerHeight,
        showGuidingText: '',
        showRecommend: false,
        questionAnimation: null,
        showPopup: false,
        selectingUser: false,
        showGuid: true,
        recomQues: [],
        defaultQues: '',
        showUserBar: true,
        // showFeedbackMask:true,
        showFeedback: false,
        switchAnswer: {}, //{index:{contents:[{prompt:'prompt1',likeType:0},{prompt:'prompt2',likeType:0}...],current:0,total:2}}
        recieving: false,
        likeType: 0,
        feedbackGroupProcessId: 0,
        isSocketed: false,
        wsDroppingAnswer: false,
        lastProcessId: '',
        activeIndex: -1,
        videoUrl: '',
        posterUrl: '',
        scrollInto: '',
        ws: undefined,
        scrollOffsetY: 0,
        orgMsg: [],
        bgImgHeight:0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

        const {
            menuId = 0,
                answeUserId = 0,
                image1id = '',
                image2id = '',
                id = '',
                image1path = '',
                image2path = '',
                title = 'GPT舌诊',
                defaultQues,
                appMenuId,
        } = options
        let token = wx.getStorageSync('token')
        if (!token) {
            wx.navigateTo({
                url: '/pages/login/index',
                success: () => {},
                fail: (err) => {
                    console.log(err)
                },
            })
        }
        let userId = JSON.parse(wx.getStorageSync('userInfo')).userId
        this.setData({
                menuId,
                userId,
                answeUserId,
                image1id,
                image2id,
                id,
                image1path,
                image2path,
                title,
                defaultQues,
                appMenuId,
            })
            /**获取当前用户信息 */
        this.initUser()
            /**进入页面处理 */
        if (id) {
            // 历史记录
            request('POST', '/applet/dialog/process/his?pageSize=1000&pageNum=1', {
                    // answeUserId,
                    // appMenuId: menuId,
                    tbDialogueMainId: id,
                })
                .then((res) => {
                    const hisList = res.data.rows
                    console.log(hisList)
                    this.formatMsgToData(hisList, true)
                    this.listenWebsocket()
                })
                .catch((err) => {
                    console.log('对话报错', err)
                })
        } else {
            /**从storage里取menulist*/
            const menuList = wx.getStorageSync('menuList')
            menuList.forEach((item) => {
                if (item.menuId == this.data.menuId) {
                    const ques = JSON.parse(item.recomQues)
                    this.setData({
                        recomQues: ques,
                        channelData: {
                            guidingText: item.guidingText,
                        },
                    })
                    this.typewriter(item.guidingText)
                }
            })
        }
        wx.onKeyboardHeightChange((res) => {
            const height = res.height
            if (systemInfo.platform === 'ios') {
                if (height !== this.data.inputHeight) {
                    this.setData({
                        inputHeight: height,
                        scrollOffsetY: height,
                    })
                }
            } else if (systemInfo.platform === 'android') {
                if (height !== this.data.inputHeight) {
                    if (this.data.inputHeight > 0) {
                        this.setData({
                            inputHeight: height,
                        })
                    } else {
                        this.setData({
                            inputHeight: this.data.inputHeight + 20,
                        })
                    }
                }
            }
            if (height === 0) {
                let f = app.globalData.footerHeight
                this.setData({
                    paddingBottom: 10 + f,
                    scrollOffsetY: 0,
                })
            } else {
                this.setData({
                    paddingBottom: 10,
                    scrollOffsetY: 0
                })
            }
        })
    },

    initUser() {
        request('POST', `/applet/answer/user/get/default/${this.data.userId}`).then(
            (res) => {
                this.setData({
                    answeUserInfo: res.data.tbAnsweUser,
                    answeUserId: res.data.tbAnsweUser.answeUserId,
                })
                if (!this.data.id) {
                    this.startDialog()
                }
            }
        )
    },
    reOpenWebsocket() {
        let that = this
        const ws = wx.connectSocket({
            url: `${baseUrl}/websocket/chat/${this.data.userId}`,
            success: function() {
                log.info(`[userId:${that.data.userId}] ws REconnect `)
                that.setData({
                    loading: false,
                })
            },
            fail: (err) => {
                log.error(`[userId:${that.data.userId}] ws REconnect failed :>>`, err)
                console.log('websocket error', err)
            },
        })
        wx.onSocketOpen(function(res) {
            that.setData({
                socketOpen: true,
            })
            wx.onSocketMessage((result) => {
                console.log('ws reslut :>> ', result)
                if (result.data === 'isOnlineSucc') {
                    return
                } else {
                    that.formatMsgToData([JSON.parse(result.data)])
                }
            })
        })
        wx.onSocketClose(function(e) {
            console.log('ws close :>> ', e);
        });
        this.setData({ ws })
    },
    listenWebsocket() {
        const {
            menuId,
            userId,
            answeUserId,
            image1id,
            image2id,
            id,
            image1path,
            image2path,
        } = this.data
        let that = this
        const ws = wx.connectSocket({
            url: `${baseUrl}/websocket/chat/${userId}`,
            success: function() {
                log.info(`[userId:${userId}] ws connect`)
                if (that.data.defaultQues) {
                    let prompt = decodeURIComponent(that.data.defaultQues)
                    let arr = that.data.dialogues
                    arr.push({
                        type: 'oner',
                        msg: that.handleTowxml(prompt, 'dark'),
                        contentType: 'text', // 文字 、图片
                    })
                    that.setData({
                        dialogues: arr,
                        loading: true,
                    })
                    request('POST', '/applet/bigmodel/chat', {
                            userId,
                            answeUserId,
                            appMenuId: menuId,
                            dialogueId: id,
                            prompt: prompt,
                        })
                        .then((res) => {
                            that.setData({
                                loading: false,
                            })
                        })
                        .catch()
                }
                // 连接对话成功后 假如是拍完照过来 则发送图片
                if (image1id) {
                    let arr = that.data.dialogues
                    const orgMsg = that.data.orgMsg
                    arr.push({
                        type: 'oner',
                        msg: '',
                        contentType: 'img-tongue', // 文字 、图片
                        imgUrl: [image1path],
                    })
                    orgMsg.push('')
                    if (image2path) {
                        arr[arr.length - 1].imgUrl.push(image2path)
                    }
                    // arr.push({
                    //     type: 'oner',
                    //     msg: '',
                    //     contentType: 'img', // 文字 、图片
                    //     imgUrl: image2path,
                    // })
                    that.setData({
                        dialogues: arr,
                        loading: true,
                        orgMsg
                    })
                    request('POST', '/applet/bigmodel/chat', {
                            userId,
                            answeUserId,
                            appMenuId: menuId,
                            dialogueId: id,
                            prompt: '',
                            image_0: image1id,
                            image_1: image2id,
                        })
                        .then((res) => {
                            that.setData({
                                loading: false,
                                isSocketed: true,
                            })
                        })
                        .catch()
                }
            },
            fail: (err) => {
                log.error(`[userId:${userId}] ws connect failed :>>`, err)
                console.log('websocket error', err)
            },
        })
        wx.onSocketOpen(function(res) {
            that.setData({
                socketOpen: true,
            })
            wx.onSocketMessage((result) => {
                console.log('ws reslut :>> ', result)
                if (result.data === 'isOnlineSucc') {
                    return
                } else {
                    // if (that.data.typing) {
                    //     let ws = that.data.wsStack
                    //     ws.push([JSON.parse(result.data)])
                    //     that.setData({wsStack: ws})
                    // } else {
                    that.formatMsgToData([JSON.parse(result.data)])
                        // }
                }
            })
        })
        wx.onSocketClose(function(e) {
            console.log('ws close :>> ', e);
        });
        this.setData({ ws })
    },
    checkWsStatus() {
        if ((!this.data.ws) || (this.data.ws.readyState == 3)) {
            this.reOpenWebsocket()
        }
    },
    formatMsgToData(list, isHistory = false) {
        /**
         * 格式化 历史消息 消息推送为页面上可以展示的消息
         * prompType==2:cv报告文字，contentType="report"，加打字机效果，显示跳转报告
         * prompType==3:大模型文字，contentType="text"，流式接收
         * else:图，contentType="img"
         */
        this.setData({ activeIndex: -1 })
        const arr = this.data.dialogues
        const orgMsg = this.data.orgMsg
        if (isHistory) {
            /**历史消息 */
            list.forEach((e) => {
                console.log('his>>', e)
                if (e.prompt === 'isOnlineSucc') {
                    return
                }
                switch (e.promptType) {
                    case 0:
                        arr.push({
                            type: e.type,
                            msg: e.type === 'oner' ?
                                this.handleTowxml(e.prompt, 'dark') : this.handleTowxml(JSON.parse(e.prompt)),
                            contentType: 'text',
                            processId: e.processId || '',
                            groupProcessId: e.groupProcessId || '',
                        })
                        orgMsg.push(e.type === 'oner' ? e.prompt : JSON.parse(e.prompt))
                        break
                    case 3:
                        arr.push({
                            type: e.type,
                            msg: e.type === 'oner' ?
                                this.handleTowxml(e.prompt, 'dark') : this.handleTowxml(JSON.parse(e.prompt)),
                            contentType: 'text',
                            processId: e.processId || '',
                            groupProcessId: e.groupProcessId || '',
                        })
                        orgMsg.push(e.type === 'oner' ? e.prompt : JSON.parse(e.prompt))
                        break
                    case 2:
                        arr.push({
                            type: e.type,
                            msg: e.type === 'oner' ?
                                this.handleTowxml(e.prompt, 'dark') : this.handleTowxml(JSON.parse(e.prompt)),
                            contentType: 'report',
                            processId: e.processId || 0,
                            groupProcessId: e.groupProcessId || '',
                        })
                        orgMsg.push(e.type === 'oner' ? e.prompt : JSON.parse(e.prompt))
                        break
                    default:
                        if (e.type == 'oner') {

                            if (arr.length != 0 && arr[arr.length - 1].contentType == 'img-tongue') {
                                arr[arr.length - 1].imgUrl.push(`data:image/png;base64,${e.prompt}`)
                            } else {
                                arr.push({
                                    type: e.type,
                                    contentType: 'img-tongue',
                                    imgUrl: [`data:image/png;base64,${e.prompt}`],
                                    processId: e.processId || 0,
                                    groupProcessId: e.groupProcessId || 0,
                                })
                            }
                            orgMsg.push('')
                        } else {
                            arr.push({
                                type: e.type,
                                contentType: 'img',
                                imgUrl: `data:image/png;base64,${e.prompt}`,
                                processId: e.processId || 0,
                                groupProcessId: e.groupProcessId || 0,
                            })
                            orgMsg.push('')
                        }
                        break
                }
                this.setData({
                    dialogues: arr,
                    orgMsg: orgMsg,
                })
            })
        } else {
            /**非历史消息 websocket一次接收到1条*/
            let t = list[0]
            if (t.recomQues) {
                const ques = JSON.parse(t.recomQues)
                if (ques !== '') {
                    this.setData({
                        recomQues: ques,
                    })
                }
            }
            if (t.type === 'doctor') {
                // console.log('doctor>>')
                switch (t.promptType) {
                    case 0:
                        arr.push({
                            type: t.type,
                            msg: this.handleTowxml(t.prompt),
                            contentType: 'text',
                            processId: t.processId || '',
                            groupProcessId: t.groupProcessId || '',
                        })
                        orgMsg.push(t.prompt)
                        this.setData({
                            dialogues: arr,
                            typing: false,
                            loading: false,
                        })
                        log.info(`[userId:${this.data.userId}][ws msg case0][processId:${t.processId}]`, t.prompt)
                        break
                    case 2:
                        /**cv=>打字机 */
                        this.setData({ typing: true })
                        arr.push({
                            type: t.type,
                            msg: this.handleTowxml(''),
                            contentType: 'report',
                            processId: t.processId || '',
                            groupProcessId: t.groupProcessId || '',
                        })
                        this.setData({
                            dialogues: arr,
                        })
                        console.log('setdialog>>', t)
                        let dialog = JSON.parse(t.prompt).split('')
                        orgMsg.push(JSON.parse(t.prompt))
                        let cnt = 1
                            // .replaceAll(/<(li|ol|ul|\/li|\/ol|\/ul)>/g, '')
                        let _this = this
                        this.i = setInterval(() => {
                            if (cnt == dialog.length) {
                                clearInterval(_this.i)
                                _this.setData({ typing: false })
                                wx.vibrateShort()
                                _this.setData({
                                        recomQues: ['我的体质是什么', '请给我一些调理建议'],
                                        showRecommend: true,
                                    })
                                    // if (list.length != 0) {
                                    //     setDialog(list, arr)
                                    // } else {
                                    //     // console.log('wsStack :>> ', JSON.stringify(_this.data.wsStack))
                                    //     if (_this.data.wsStack.length != 0) {
                                    //         let wsStack = _this.data.wsStack
                                    //         let nextItem = wsStack.shift()
                                    //         _this.formatMsgToData(nextItem)
                                    //     } else {
                                    //         _this.setData({ loading: false })
                                    //         if (_this.data.recomQues.length != 0) {
                                    //             this.setData({ showRecommend: true })
                                    //         }
                                    //     }
                                    // }
                            } else {
                                arr[arr.length - 1].msg = this.handleTowxml(dialog.slice(0, cnt).join(''))
                                _this.setData({
                                    dialogues: arr,
                                })
                                cnt++
                            }
                        }, 50)
                        log.info(`[userId:${this.data.userId}][ws msg case2][processId:${t.processId}]`, t.prompt)
                        break
                    case 3:
                        // console.log('case3>>',t)
                        /**流式回答 */
                        if (t.isFinish == -1) {
                            /**第一次接收 */
                            let lastProcessId = arr[arr.length - 1].processId
                            let content = {
                                type: t.type,
                                msg: this.handleTowxml(JSON.parse(t.prompt)),
                                contentType: 'text',
                                processId: t.processId || '',
                                groupProcessId: t.groupProcessId || '',
                                likeType: 0,
                            }
                            if (t.processId == lastProcessId) {
                                /**processId和最后一条一样=>重新生成的答案*/
                                arr[arr.length - 1] = content
                                orgMsg[arr.length - 1] = JSON.parse(t.prompt)
                                let switchAnswer = this.data.switchAnswer
                                switchAnswer[arr.length - 1].total += 1
                                switchAnswer[arr.length - 1].current =
                                    switchAnswer[arr.length - 1].total
                                this.setData({ switchAnswer })
                            } else {
                                /**新回答 */
                                arr.push(content)
                                orgMsg.push(JSON.parse(t.prompt))
                            }
                            this.setData({ typing: true })
                            this.setData({ dialogues: arr })
                            log.info(`[userId:${this.data.userId}][ws msg case3][start][processId:${t.processId}]`, t.prompt)
                        } else if (t.isFinish == 0) {
                            /**继续接收 */
                            if (this.data.wsDroppingAnswer) {
                                console.log(
                                        'wsDroppingAnswer>>',
                                        this.data.wsDroppingAnswer,
                                        t.isFinish
                                    )
                                    /**已点停止生成 */
                                return
                            }
                            console.log('ws answer>>', t.isFinish)
                            arr[arr.length - 1].msg = this.handleTowxml(JSON.parse(t.prompt))
                            orgMsg[arr.length - 1] = JSON.parse(t.prompt)
                            this.setData({ dialogues: arr })
                        } else {
                            /**结束 */
                            if (!this.data.wsDroppingAnswer) {
                                arr[arr.length - 1].msg = this.handleTowxml(JSON.parse(t.prompt))
                                orgMsg[arr.length - 1] = JSON.parse(t.prompt)
                                this.setData({ dialogues: arr })
                                wx.vibrateShort()
                            }
                            this.setData({
                                typing: false,
                                loading: false,
                                wsDroppingAnswer: false,
                            })
                            if (this.data.recomQues.length > 0) {
                                this.setData({ showRecommend: true })
                            }
                            /**存到switchAnswer */
                            this.addToAnswersList(arr[arr.length - 1], arr.length - 1)
                            log.info(`[userId:${this.data.userId}][ws msg case3][end][processId:${t.processId}]`, t.prompt)
                        }

                        break
                    default:
                        arr.push({
                            type: t.type,
                            contentType: 'img',
                            imgUrl: `data:image/png;base64,${t.prompt}`,
                            processId: t.processId || '',
                            groupProcessId: t.groupProcessId || '',
                        })
                        orgMsg.push('')
                }
            } else {
                /**其他情况：正常 */
                if (t.prompt === 'isOnlineSucc') {
                    return
                }
                if (t.promptType === 0) {
                    arr.push({
                        type: t.type,
                        msg: t.type === 'oner' ?
                            t.prompt : JSON.parse(t.prompt).replace(/\n\n/g, '<br>'),
                        contentType: 'text',
                        processId: t.processId || '',
                        groupProcessId: t.groupProcessId || '',
                    })
                    orgMsg.push(JSON.parse(t.prompt))
                } else {
                    arr.push({
                        type: t.type,
                        contentType: 'img',
                        imgUrl: `data:image/png;base64,${t.prompt}`,
                        processId: t.processId || '',
                        groupProcessId: t.groupProcessId || '',
                    })
                    orgMsg.push('')
                }
                this.setData({
                    dialogues: arr,
                    loading: false,
                    typing: false,
                })
            }
            this.setData({ orgMsg })
        }
    },
    typewriter(text) {
        /**打字机效果 欢迎语*/
        console.log('typing')
        if (text != null) {
            let texts = text.split('')
            this.setData({
                typing: true,
            })
            let t = setInterval(() => {
                if (texts.length === 0) {
                    clearInterval(t)
                    this.setData({ typing: false, showRecommend: true })
                    wx.vibrateShort()
                        // this.setData({showPopup:true,selectingUser:true})
                } else {
                    let showGuidingText = this.data.showGuidingText
                    let n = texts.shift()
                    showGuidingText += n
                    this.setData({ showGuidingText })
                }
            }, 10)
        }
    },
    handleCamera() {
        const { menuId, userId, answeUserId, id } = this.data
        wx.navigateTo({
            url: `/pages/camera/index?id=${id}&menuId=${menuId}&userId=${userId}&answeUserId=${answeUserId}`,
        })
    },
    handleRefresh() {
        this.checkWsStatus()
        const { id } = this.data
        request('POST', '/applet/dialog/refreshDig', {
                id,
            })
            .then(res => {

                this.setData({ recomQues: [] })
            })
            .catch()
    },
    handleBlur() {},
    handleInput(e) {
        if (this.data.loading) {
            wx.showToast({
                title: '正在生成，请稍候',
                icon: 'none',
            })
            return
        }
        if (this.data.msg == '') {
            return
        }
        console.log('handel input ', e)
        this.setData({ showRecommend: false, showGuid: false })
        let arr = this.data.dialogues
        let orgMsg = this.data.orgMsg
        arr.push({
            type: 'oner',
            msg: this.handleTowxml(this.data.msg, 'dark'),
            contentType: 'text',
        })
        orgMsg.push(this.data.msg)
        this.chat(e.detail.value || this.data.msg)
        this.setData({
            dialogues: arr,
            msg: '',
            inputHeight: 0,
            orgMsg: orgMsg
        })
    },
    handleInputChange(e) {
        // console.log(e.detail.value)
        this.setData({
            msg: e.detail.value,
        })
    },
    handleButton(e) {
        if (!this.data.loading) {
            this.handleInput(e)
        } else {
            if (!this.data.typing) {
                wx.showToast({
                    title: '正在加载，请稍候',
                    icon: 'none',
                })
            } else {
                if (this.hasOwnProperty('i')) {
                    /**打字机中 */
                    clearInterval(this.i)
                    this.setData({ loading: false, typing: false, wsStack: [] })
                    wx.showToast({
                        title: '已停止生成',
                        icon: 'none',
                    })
                }
                if (!this.data.wsDroppingAnswer) {
                    /**ws接收中 */
                    console.log('stop ws')
                    this.requireStop()
                    this.setData({
                        typing: false,
                        loading: false,
                        // wsDroppingAnswer: true,
                    })
                }
                // wx.showToast({
                //     title: '已停止生成',
                //     icon: 'none',
                // })
            }
        }
    },
    handleInputHeightChange(e) {
        // console.log('iosheight', e)
        // wx.onKeyboardHeightChange((result) => { console.log('result :>> ', result); })
        // const height = e.detail.height;
        // if (height === 0) {
        //   this.setData({
        //     inputHeight: 0
        //   })
        //   return;
        // }
        // if (e.detail.height * 2 !== this.data.inputHeight) {
        //   this.setData({
        //     inputHeight: e.detail.height * 2
        //   })
        // }
    },
    bindblur() {
        this.setData({
            inputHeight: 0,
        })
    },
    chat(msg) {
        const { userId, answeUserId, appMenuId, dialogueId, id } = this.data
        this.checkWsStatus()
        if (this.data.loading) {
            return
        }
        if (msg.length === 0) {
            return
        }
        this.setData({ loading: true })
        request('POST', '/applet/bigmodel/chat', {
                userId,
                answeUserId,
                appMenuId,
                dialogueId: id,
                prompt: msg,
            })
            .then((res) => {})
            .catch((err) => {
                wx.showToast({
                    title: err.msg,
                    icon: 'error',
                })
                this.setData({ loading: false })
            })
    },
    handleQuestion(e) {
        if (this.data.loading) {
            return
        }
        let msg = this.data.recomQues[e.currentTarget.dataset.index]
        const arr = this.data.dialogues
        const orgMsg = this.data.orgMsg
        arr.push({
            type: 'oner',
            msg: this.handleTowxml(msg, 'dark'),
            contentType: 'text',
        })
        orgMsg.push(msg)
        this.setData({
            dialogues: arr,
            showRecommend: false,
            showGuid: false,
            recomQues: [],
            orgMsg
        })
        this.chat(msg)
    },
    handelGoReport(e) {
        const index = e.currentTarget.dataset.index
        const item = this.data.dialogues[index]
        console.log('go report>>', item)
        wx.navigateTo({
            url: `/pages/report-detail/index?id=${item.processId}&dialogId=${this.data.id}`,
        })
    },
    handlePreview(e) {
        const { type, id, url } = e.currentTarget.dataset
        let that = this
        if (id) {
            if (type === 'doctor') {
                wx.navigateTo({
                    url: `/pages/report-detail/index?id=${id}&dialogId=${that.data.id}`,
                })
            } else {
                wx.previewImage({
                    urls: [url],
                    success: (res) => {
                        console.log(res)
                    },
                    fail: (err) => {
                        console.log('err', err)
                    },
                })
            }
        }
    },
    animation() {
        let ani = wx.createAnimation()
        ani.translateX(500)
        this.setData({ questionAnimation: ani.export() })
    },
    showSelectUser() {
        this.setData({ showPopup: true })
    },
    handelSelectUser(e) {
        const { answeUserId } = e.detail
        // if(answeUserId==this.data.answeUserId){
        //   this.setData({ showPopup: false, selectingUser: false })
        //   return}
        this.setData({ showPopup: false, selectingUser: false, answeUserId })
            /**设置为当前用户 */
        request('POST', `/applet/answer/user/setDefault`, { answeUserId }).then(
                (res) => {
                    /**重新进入对话页面开始新对话 */
                    wx.redirectTo({
                        url: `/pages/channel/index?menuId=${this.data.menuId}&title=${this.data.title}&userId=${this.data.userId}`,
                    })
                }
            )
            /**更新userbar信息 */
            // request("POST", `/applet/answer/user/get/${answeUserId}`).then(res => {
            //   const answeUserInfo = res.data
            //   this.setData({answeUserInfo})
            // })

        /**开始对话 */
        // this.startDialog()
        // request('POST', '/applet/dialog/creatNewDig', {
        //     answeUserId:answeUserId,
        //     appMenuId: this.data.menuId,
        //     userId:this.data.userId
        // }).then(res => {
        //     this.setData({
        //         dialogueId: res.data.id,
        //         id: res.data.id,
        //         channelData: {
        //             ...res.data
        //         }
        //     })
        //     let that = this
        //     this.listenWebsocket()
        // }).catch()
    },
    startDialog() {
        request('POST', '/applet/dialog/creatNewDig', {
                answeUserId: this.data.answeUserInfo.answeUserId,
                appMenuId: this.data.menuId,
                userId: this.data.userId,
            })
            .then((res) => {
                this.setData({
                    dialogueId: res.data.id,
                    id: res.data.id,
                    channelData: {
                        ...res.data,
                    },
                })
                let that = this
                this.listenWebsocket()
            })
            .catch()
    },
    hideUserSelect() {
        this.setData({ showPopup: false })
        request('POST', `/applet/answer/user/get/default/${this.data.userId}`).then(
          (res) => {
              this.setData({
                  answeUserInfo: res.data.tbAnsweUser,
                  answeUserId: res.data.tbAnsweUser.answeUserId,
              })
          }
      )
    },
    editUserInfo() {
        this.setData({ showPopup: true, selectingUser: true })
    },
    hideUserBar() {
        const status = this.data.showUserBar
        this.setData({ showUserBar: !status })
    },
    hideFeedbackPopup() {
        console.log('hideFeedbackPopup')
        this.setData({ showFeedback: false })
    },
    handelCopy(e) {
        console.log('copy e:>>', e)
        const content = e.currentTarget.dataset.content
        wx.setClipboardData({
            data: content,
            success(res) {},
        })
    },
    handelDissatisfied(params) {
        this.setData({
            showFeedback: true,
            feedbackGroupProcessId: params.groupProcessId,
        })
    },
    feedbackStatusChange(e) {
        console.log('change feedback>>', e)
        this.setData({ likeType: e.detail.likeType })
        let index = e.currentTarget.dataset.index
        if (e.detail.likeType == 2) {
            /**点踩 */
            this.handelDissatisfied(e.detail)
        } else {
            /**点赞or取消 */
            request('POST', '/applet/dialog/group/like', e.detail).then((res) => {
                if (e.detail.likeType == 1) {
                    wx.showToast({
                        title: '感谢您的反馈',
                    })
                }
            })
        }
        this.handelReanswerFeedback(index, e.detail.likeType)
    },
    handelReanswerFeedback(index, likeType) {
        /**更新点赞状态 */
        console.log('handelReanswerFeedback')
        let switchAnswer = this.data.switchAnswer
        try {
            switchAnswer[index].contents[switchAnswer[index].current - 1].likeType =
                likeType
            switchAnswer[index].currentLiketype = likeType
            this.setData({ switchAnswer })
        } catch (err) {
            console.log('err in handelReanswerFeedback:>> ', err)
        }
    },
    handelReanswer(e) {
        /**清空要重新回答内容 */
        this.checkWsStatus()
        console.log(e)
        const index = e.currentTarget.dataset.index
        const arr = this.data.dialogues
        let currentAnswer = this.data.dialogues[index]
        currentAnswer.msg = ''
        arr[arr.length - 1] = currentAnswer
        this.setData({ dialogues: arr, loading: true })
        let processId = this.data.dialogues[index].processId
        request('POST', '/applet/bigmodel/reanswer', { processId }).then((res) => {
            console.log('reanswer>>', res)
        })
    },
    addToAnswersList(arrObject, index) {
        /**存进switchAnswer */
        let switchAnswer = this.data.switchAnswer
        if (switchAnswer[index]) {
            //该问题已有多个回答
            switchAnswer[index].contents.push({
                prompt: JSON.stringify(arrObject),
                likeType: null,
            })
            switchAnswer[index].currentLiketype = 0
        } else {
            //第一次重新回答
            switchAnswer[index] = {
                contents: [{ prompt: JSON.stringify(arrObject), likeType: 0 }],
                currentLiketype: 0,
                current: 1,
                total: 1,
            }
        }
        this.setData({ switchAnswer })
            // console.log('save switchAnswer>>', this.data.switchAnswer)
    },
    handelSwitchAnswer(e) {
        let switchType = e.detail
        let index = e.currentTarget.dataset.index
        let dialogues = this.data.dialogues
        let switchAnswer = this.data.switchAnswer
        let currentSwitchAnswer = this.data.switchAnswer[index]
            // console.log('switch>>', JSON.stringify(currentSwitchAnswer))
        if (switchType == -1) {
            if (currentSwitchAnswer.current == 1) {
                return
            } else {
                currentSwitchAnswer.current -= 1
                currentSwitchAnswer.currentLiketype =
                    currentSwitchAnswer.contents[currentSwitchAnswer.current - 1].likeType
                dialogues[index] = JSON.parse(
                    currentSwitchAnswer.contents[currentSwitchAnswer.current - 1].prompt
                )
            }
        } else {
            if (currentSwitchAnswer.current == currentSwitchAnswer.total) {
                return
            } else {
                currentSwitchAnswer.current += 1
                currentSwitchAnswer.currentLiketype =
                    currentSwitchAnswer.contents[currentSwitchAnswer.current - 1].likeType
                dialogues[index] = JSON.parse(
                    currentSwitchAnswer.contents[currentSwitchAnswer.current - 1].prompt
                )
            }
        }
        switchAnswer[index] = currentSwitchAnswer
        this.setData({ switchAnswer, dialogues, activeIndex: index })
    },
    linktap(src) {
        console.log('linktap :>> ', src);
        const fileUrl = src
        const lastIndexOfDot = fileUrl.lastIndexOf('.')
        const extension = fileUrl.slice(lastIndexOfDot + 1)
        let type = 0
        console.log('extension ->>', extension)
        switch (extension) {
            case 'jpg':
            case 'jpeg':
            case 'png':
            case 'gif':
                type = 1 // 图片类型
                break
            case 'mp4':
            case 'avi':
            case 'mov':
            case 'wmv':
                type = 2 // 视频类型
                break
            default:
                type = 0 // 其他未知类型
                break
        }
        console.log('type --> ', type)
        if (type === 1) {
            wx.previewImage({
                current: fileUrl,
                urls: [fileUrl],
            })
        }
        if (type === 2) {
            // 在首页的JS代码中
            wx.navigateTo({
                url: `/pages/channel/video-player/video-player?videoUrl=${fileUrl}&posterUrl=${fileUrl}`,
            })
        }
    },
    handleTowxml(text, theme = 'light') {

        return towxml(text, 'markdown', {
            theme: theme,
            events: {
                tap: (e) => {
                    console.log('towxml tap :>> ', e);
                    try {
                        let src = e.currentTarget.dataset.data.attrs.href
                        if (src) {
                            this.linktap(src)
                        }
                    } catch (e) {
                        console.log('towxml handel tap error :>> ', e);
                    }

                }
            }
        })
    },
    requireStop() {
        request('POST', '/applet/bigmodel/break', { userId: this.data.userId }).then((res) => {
            if (res.code == 200) {
                wx.showToast({
                        title: '已停止生成',
                        icon: 'none',
                    })
                    // this.checkWsStatus()
            }

        })
    },
    handelScrollInto(i) {},
    handelCopy(e) {
        console.log('copy e :>> ', e);
        let index = e.currentTarget.dataset.index
        let text = this.data.orgMsg[index]
        text = text.replaceAll(/<a\b[^>]*>(.*?)<\/a>/g, '$1')
        console.log('copy text :>> ', text);
        wx.setClipboardData({
            data: text,
            success(res) {
                console.log('copy success :>> ');
            }
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
      setTimeout(()=>{
        let q = wx.createSelectorQuery()
      q.select('#navbar').boundingClientRect(rect=>{
        console.log("boundingClientRect >>",rect)
        this.setData({bgImgHeight:rect.height})
      }).exec()},300)
      
    },

    onShow() {
        console.log('channel show')
        const userInfo = wx.getStorageSync('userInfo')
        if (!userInfo) {
            wx.navigateTo({
                url: '/home/pages/login',
            })
        } else {
            this.setData({ userInfo })
        }
        // let pages=getCurrentPages()
        // console.log('current pages>>',pages)
        if (this.data.selectingUser) {
            this.setData({ showPopup: true })
        }
        if (this.data.isSocketed) {
            this.reOpenWebsocket()
        }
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        console.log('channel hide')
        wx.closeSocket()
        this.setData({ showPopup: false, isSocketed: true })
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        console.log('channel unload')
        wx.closeSocket()
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {},

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {},
})